package org.example.dao;

import org.example.DBConnection;
import org.example.entity.OrderItem;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaomengzi
 * @create 2025-08-04 下午2:52
 */
public class OrderItemDAO {
    Connection connection;
    public OrderItemDAO() throws SQLException {
        connection = DBConnection.getConnection();
        if(connection == null){
            throw new SQLException("数据库连接失败");
        }
    }
    //创建订单项
    public int createOrderItem(OrderItem orderItem) throws SQLException {
        String sql = "insert into order_items (order_id,product_id,quantity,unit_price) values (?,?,?,?)";
        try (PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setInt(1, orderItem.getOrderId());
            ps.setInt(2, orderItem.getProductId());
            ps.setInt(3, orderItem.getQuantity());
            ps.setBigDecimal(4, orderItem.getUnitprice());
            try (ResultSet rs = ps.executeQuery()) {
               int orderItemId = rs.getInt(1);
                if (orderItemId > 0) {
                    orderItem.setId(orderItemId);
                }
                return orderItemId;
            }
        }
    }
    //通过订单id获取所有订单项
    public ArrayList<OrderItem> getOrderItems(int orderId) throws SQLException {
        String sql = "select * from order_items where order_id = ?";
        List<OrderItem> orderItems = new ArrayList<OrderItem>();
        try (PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setInt(1, orderId);
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    OrderItem orderItem = new OrderItem();
                    orderItem.setId(rs.getInt("id"));
                    orderItem.setOrderId(rs.getInt("order_id"));
                    orderItem.setProductId(rs.getInt("product_id"));
                    orderItem.setQuantity(rs.getInt("quantity"));
                    orderItem.setUnitprice(rs.getBigDecimal("unit_price"));
                    orderItems.add(orderItem);
                }
                return orderItems;
            }
        }
    }

}
